#include <iostream>
using std::cout;
using std::endl;

template <class Type>
struct MyDefaultDeleter
{
    void operator()(Type* p)
    {
        if(p) {
            delete p;
        }
    }
};

template <class T, class Deleter = MyDefaultDeleter<T>>
class RAII
{
public:
    explicit
    RAII(T * data)
    : _data(data)
    {}

    RAII(const RAII &) = delete;
    RAII&operator=(const RAII&) = delete;

    T * operator->()
    {   return _data;   }

    T & operator*()
    {   return *_data;  }

    T * get() { return _data;   }


    ~RAII(){
        if(_data) {
            //delete _data;
            _deleter(_data);//使用函数对象定制化资源回收的方式
            _data = nullptr;
        }
    }

private:
    Deleter _deleter;
    T * _data;//_data指向的就是堆空间的数据
}; 

class Point
{
public:
    Point(int ix = 0, int iy = 0)
    : _ix(ix)
    , _iy(iy)
    {   cout << "Point(int,int)" << endl;   }

    ~Point() {  cout << "~Point()" << endl; }

    void print() const
    {   cout << "(" << _ix << "," << _iy << ")" << endl;}

private:
    int _ix;
    int _iy;
};

void test0()
{
    MyDefaultDeleter<Point> mydeleter;
    Point * pt = new Point(1, 2);
    mydeleter(pt);
}

struct Myfpcloser
{
    void operator()(FILE * fp) 
    {
        if(fp){ 
            fclose(fp);
            cout << "fclose(fp)" << endl;
        }
    }
};

void test1()
{
    RAII<Point> raii(new Point(11, 12));
    raii->print();

    RAII<FILE, Myfpcloser> raii2(fopen("test.txt", "a+"));
    std::string msg("this is a new test\n");
    fwrite(msg.c_str(), 1, msg.size(), raii2.get());
}


int main()
{
    /* test0(); */
    test1();
    return 0;
}

